//
//  UIView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/28.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

extension UIView {
    
    func creatBaseAnimation(fromValue:CGPoint , toValue:CGPoint ,duration:CGFloat , keyName:String) -> Void {
        var  animation:CABasicAnimation;
        animation = CABasicAnimation(keyPath: keyName)
        animation.duration = CFTimeInterval(duration)
        animation.fromValue = NSValue(cgPoint: fromValue)
        animation.toValue = NSValue(cgPoint: toValue)
        animation.isRemovedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false
        self.layer.add(animation, forKey: keyName)
    }
    
}


extension UIView {
    
    func viewController() -> UIViewController? {
        guard let supView = self.superview else { return nil }
        let responder = supView.next
        if let res = responder as? UIViewController  {
            return res
        }
        return supView.viewController()
    }
    
    func parentController() ->UIViewController?{
        var responder = self.next
        while (responder != nil) {
            if (responder?.isKind(of: UIViewController.self))! {
                return (responder as? UIViewController)!
            }
            responder = responder?.next
        }
        return nil
    }
}


let CSMaxWidthScale            = 0.8;  //最大宽度比例
let CSMaxHeightScale           = 0.8;  //最大高度比例
let CSHorizontalPadding        = 10.0; //横排间距
let CSVerticalPadding          = 10.0; //竖排间距
let CSFitPadding               = 60.0; //居上或居下的间距
let CSCornerRadius             = 5.0;  //显示图圆角大小
let CSOpacity                  = 0.8;  //不透明度
let CSFontSize                 = 16.0; //显示文字大小
let CSMaxTitleLines            = 0;    //标题最大显示行数（0表示可换行）
let CSMaxMessageLines          = 0;    //信息最大显示行数（0表示可换行）
let CSFadeDuration             = 0.2;  //消失时间
let CSDisplayDuration          = 2.0;  //默认显示时长
let CSShadowOpacity            = 0.8;  //阴影不透明度
let CSShadowRadius             = 2.0;  //阴影半径
let CSImageViewWidth           = 80.0; //设置图片的最大宽度
let CSImageViewHeight          = 80.0; //设置图片的最大高度
let CSDefaultPosition       = "center"; //默认显示在底部
let TAG_OF_MESSAGE_VIEW = 99990

extension UIView {
    func displayMessage(message:String) {
        self.displayMessage(message: message, duration: CGFloat(CSDisplayDuration), position: CSDefaultPosition as AnyObject)
    }
    
    func displayMessage(message:String, duration interval:CGFloat,position:AnyObject) {
         let view = self.viewForMessage(message: message, title: nil, image: nil)
        self.displayView(view: view!, interval: interval, point: position)
    }
    func displayView(view:UIView, interval:CGFloat, point:AnyObject) {
        view.center = self.centerPointForPosition(point: point, superView: view)
        view.alpha = 0.0;
        self.addSubview(view)
        UIView.animate(withDuration: CSFadeDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
            view.alpha = 1.0
        }) { (finished) in
            UIView.animate(withDuration: CSFadeDuration, delay: TimeInterval(interval), options:UIViewAnimationOptions.curveEaseIn, animations: {
                view.alpha = 0.0;
            }, completion: { (finished) in
                view.removeFromSuperview()
            })
        }
    }
    
    func centerPointForPosition(point:AnyObject, superView:UIView) -> CGPoint{
        if point.isKind(of: NSString.self) {
            if (point as! NSString).caseInsensitiveCompare("top") == ComparisonResult.orderedSame{
                return CGPoint(x: self.bounds.size.width/2, y: (superView.frame.size.height / 2) + CGFloat(CSFitPadding))
            }else  if (point as! NSString).caseInsensitiveCompare("bottom") == ComparisonResult.orderedSame {
                return CGPoint(x: self.bounds.size.width/2, y: (superView.frame.size.height / 2) + (self.bounds.size.height - (superView.frame.size.height / 2)) - CGFloat(CSFitPadding))
            }else  if (point as! NSString).caseInsensitiveCompare("center") == ComparisonResult.orderedSame {
                return CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
            }
        }else if point.isKind(of: NSValue.self){
            return (point as! NSValue).cgPointValue
        }
        return self.centerPointForPosition(point:CSDefaultPosition as AnyObject, superView:superView)
        
    }
    
    
    
    func viewForMessage(message:String?, title:String?, image:UIImage?) -> UIView?{
        if message == nil && title == nil && image == nil {
            return nil
        }
        var messageLabel:UILabel? = nil
        var titleLabel:UILabel? = nil
        var imageView:UIImageView? = nil
        
        var wrapperView = self.viewWithTag(TAG_OF_MESSAGE_VIEW)
        if wrapperView == nil {
            wrapperView = UIView()
            wrapperView?.tag = TAG_OF_MESSAGE_VIEW
        }
        wrapperView?.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue((UInt8(UIViewAutoresizing.flexibleLeftMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleRightMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleTopMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleBottomMargin.rawValue))))
        wrapperView?.layer.cornerRadius = 5.0
        wrapperView?.layer.shadowColor = UIColor.black.cgColor;
        wrapperView?.layer.shadowOpacity = 0.8;
        wrapperView?.layer.shadowRadius = 2.0;
        wrapperView?.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
        wrapperView?.backgroundColor = UIColor.black.withAlphaComponent(0.8)
        if image != nil {
            imageView = UIImageView(image: image)
            imageView?.contentMode = UIViewContentMode.scaleAspectFit
            imageView?.frame = CGRect(x: 10, y: 10, width: 80, height: 80)
            
        }
        var imageWidth:CGFloat
        var imageHeight:CGFloat
        var imageLeft:CGFloat
        
        if imageView != nil {
            imageWidth = (imageView?.bounds.size.width)!
            imageHeight = (imageView?.bounds.size.height)!
            imageLeft = 10
        }else {
            imageWidth = 0.0
            imageHeight = 0.0
            imageLeft = 0.0
        }
        
        if title != nil {
            titleLabel = UILabel()
            titleLabel?.numberOfLines = 0
            titleLabel?.font = UIFont.boldSystemFont(ofSize: 16);
            titleLabel?.textAlignment = NSTextAlignment.left;
            titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;
            titleLabel?.textColor = UIColor.white
            titleLabel?.backgroundColor = UIColor.clear
            titleLabel?.alpha = 1.0;
            titleLabel?.text = title;
            let maxSizeTtilte = CGSize(width: self.bounds.size.width * 0.8, height: self.bounds.size.width * 0.8)
            let expectedSizeTitle = (title! as NSString).sizeWithConstrainedSize(size: maxSizeTtilte, font: (titleLabel?.font)!, lineSpacing: 0)
            titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: expectedSizeTitle.width, height: expectedSizeTitle.height)
            
        }
        if message != nil {
            messageLabel = UILabel()
            messageLabel?.numberOfLines = 0;
            messageLabel?.font = UIFont.systemFont(ofSize: 16.0)
            messageLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;
            messageLabel?.textColor = UIColor.white;
            messageLabel?.backgroundColor = UIColor.clear
            messageLabel?.alpha = 1.0;
            messageLabel?.text = message;
            let maxSizeMessage = CGSize(width: self.bounds.width * 0.8, height: self.bounds.size.height * 0.8)
            let expectedSizeMessage = (message! as NSString).sizeWithConstrainedSize(size: maxSizeMessage, font: (messageLabel?.font)!, lineSpacing: 0)
            messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: expectedSizeMessage.width, height: expectedSizeMessage.height)
        }
        var titleWidth:CGFloat
        var titleHeight:CGFloat
        var titleTop:CGFloat
        var titleLeft:CGFloat
        
        if title != nil {
            titleWidth = (titleLabel?.bounds.size.width)!;
            titleHeight = (titleLabel?.bounds.size.height)!;
            titleTop = 10;
            titleLeft = imageLeft + imageWidth + 10
        }else {
            titleWidth = 0.0
            titleHeight = 0.0
            titleTop = 0.0
            titleLeft = 0.0
        }
        var messageWidth:CGFloat
        var messageHeight:CGFloat
        var messageLeft:CGFloat
        var  messageTop:CGFloat
        
        if messageLabel != nil {
            messageWidth = (messageLabel?.bounds.size.width)!;
            messageHeight = (messageLabel?.bounds.size.height)!
            messageLeft = imageLeft + imageWidth + 10;
            messageTop = titleTop + titleHeight + 10;
        }else {
            messageWidth = 0.0
            messageHeight = 0.0
            messageLeft = 0.0
            messageTop = 0.0
        }
        
        let longerWidth = max(titleWidth, messageWidth)
        let longerLeft = max(titleLeft, messageLeft)
        let wrapperWidth = max((imageWidth + CGFloat((CSHorizontalPadding * 2))), (longerLeft + longerWidth + CGFloat( CSHorizontalPadding)))
        
        let wrapperHeight = max((messageTop + messageHeight + CGFloat(CSVerticalPadding)), (imageHeight + CGFloat(CSVerticalPadding * 2)))
        wrapperView?.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight)
        if titleLabel != nil {
            titleLabel?.frame = CGRect(x: titleLeft, y: titleTop, width: titleWidth, height: titleHeight);
            wrapperView?.addSubview(titleLabel!)
        }
        if messageLabel != nil {
            messageLabel?.frame = CGRect(x: messageLeft, y: messageTop, width: messageWidth, height: messageHeight);
            wrapperView?.addSubview(messageLabel!)
        }
        if imageView != nil {
            wrapperView?.addSubview(imageView!)
        }
        
        return wrapperView
        
    }
    
}
